import axios from 'axios';
import store from '@/store';
import { Dialog, Toast } from 'vant';

let loadingCount = 0;
const baseUrl = process.env.VUE_APP_BASE_API;
// create an axios instance

console.log('baseUrl', baseUrl);
const service = axios.create({
    baseURL: baseUrl, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 15000, // request timeout
});

// request interceptor
service.interceptors.request.use(
    config => {
        // Toast.loading({
        //     message: store.state.tipMessage,
        //     forbidClick: true,
        //     duration: 0,
        // });
        loadingCount += 1;
        config.headers['Access-Control-Allow-Origin'] = '*';
        config.headers['openid'] = store.state.userInfo.openid;
        config.headers['unionid'] = store.state.userInfo.unionid;
        config.headers['appid'] = store.state.userInfo.appid;

        if (config.url.startsWith('/avatar_composition')) {
            // config.url = config.url.slice(9);
            config.baseURL = process.env.VUE_APP_MAKE_IMG_API;
        }
        return config;
    },
    error => {
        // do something with request error
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        handleLoadingDecrease();
        const res = response.data;
        // if the custom code is not 20000, it is judged as an error.
        if (response.status !== 200) {
            return Promise.reject(new Error(response.statusText || 'Error'));
        } else {
            let code = res.code.toLowerCase();
            if (code === 'ok' || code === 'success') {
                return res.data;
            } else {
                Dialog.alert({
                    message: res.msg,
                });
                return Promise.reject(new Error(res.msg || 'Error'));
            }
        }
    },
    error => {
        console.error('err' + error); // for debug
        handleLoadingDecrease();
        if (error.response && error.response.status === 401) {
            // store.dispatch('user/login').then(() => {
            //     console.log('login success');
            // });
        } else {
            Dialog.alert({
                message: error.message,
            });
        }
        return Promise.reject(error);
    }
);

export default {
    get: (url, params) => {
        return service({
            method: 'get',
            url,
            params,
        });
    },
    post: (url, data) => {
        return service({
            method: 'post',
            url,
            data,
        });
    },
    put: (url, data) => {
        return service({
            method: 'put',
            url,
            data,
        });
    },
    delete: (url, data) => {
        return service({
            method: 'delete',
            url,
            data,
        });
    },
};

function handleLoadingDecrease() {
    loadingCount -= 1;
    if (loadingCount <= 0) {
        Toast.clear();
    }
}
